<template>
	<view>
		<custom-nav :title="'详情'"></custom-nav>
		<view class="f36 box">
			<view>
				<!-- 头 -->
				<view class="df ac pt20 pb20 mb30 container">
					<view>
						<view class="f36 text-clamp-1">{{
							`${
								instanceData.owner.name ||
								instanceData.staterUser.name
							}提交的${instanceData.processDefName}`
						}}</view>
						<view class="instance-name">{{ selectedCompany }}</view>
						<view :style="'color:' + status.color" class="f28">{{
							status.text
						}}</view>
					</view>
					<image
						class="status-image"
						v-if="status.img"
						:src="status.img"
					></image>
				</view>
				<!-- 智能表单 -->
				<associate-form
					v-if="isAssociateForm"
					:title="associateFormTitle"
					:data="associateFormData"
				></associate-form>
				<!-- 中 -->
				<view class="mt30 mb30 container" style="margin-left: -20rpx"
					><formDesign :data="instanceData"></formDesign
				></view>
				<!--下 -->
				<!-- {{ instanceData.progress.length }} -->
				<view>
					<processProgress
						:result="instanceData.result"
						:progress="instanceData.progress"
						:processList="processList"
						:title="
							instanceData &&
							instanceData.cancelProgress &&
							instanceData.cancelProgress.length > 0
								? '原有流程'
								: '流程'
						"
					/>
				</view>
				<view
					class="mt30"
					v-if="
						instanceData &&
						instanceData.cancelProgress &&
						instanceData.cancelProgress.length > 0
					"
				>
					<view
						class="mt30"
						v-if="instanceData.cancelProgress.length > 0"
					>
						<processProgress
							:result="instanceData.result"
							:progress="instanceData.cancelProgress"
							:processList="cancelProgressList"
							:title="'撤销流程'"
						/>
					</view>
				</view>
				<!-- button 操作 -->
				<view class="actions">
					<view class="flex-center mr10">
						<view class="flex-1 f28 tc g3">
							<view
								@tap="openMoreBtn"
								v-if="
									rootTasks.length > 0 &&
									(activeTasks.length > 0 ||
										auditTasks.length > 0) &&
									recallRoot.length === 1
								"
							>
								<image
									style="width: 48rpx; height: 48rpx"
									src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/s3excyu0pwpuw6ut1n8oipcw4.png"
								></image>
								<view>更多</view>
							</view>
							<view
								v-else
								@click="handler('comment')"
								class="flex-1 f28 tc g3"
							>
								<image
									style="width: 48rpx; height: 48rpx"
									src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/37v3un3ajbxattokrfcw0nqk5.png"
								></image>
								<view>评论</view>
							</view>
						</view>
						<view
							@click="handler('cancel')"
							class="flex-1 tc g3 f28"
							v-if="
								rootTasks.length > 0 &&
								(activeTasks.length === 0 ||
									recallRoot.length > 1)
							"
						>
							<image
								style="width: 48rpx; height: 48rpx"
								:src="cancelStatus.image"
							></image>
							<view :class="cancelStatus.status ? 'g3' : 'g9'"
								>撤销</view
							>
						</view>
						<view
							@click="submitAgain"
							class="flex-1 tc g3 f28"
							v-if="
								rootTasks.length > 0 &&
								activeTasks.length === 0 &&
								recallRoot.length === 1
							"
							:class="activeTasks.length > 0 ? 'pr20' : ''"
						>
							<image
								style="width: 48rpx; height: 48rpx"
								src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/qwrzlynz12ygk34udk10ma8ob.png"
							></image>
							<view>再次提交</view>
						</view>
						<view
							@click="handler('recall')"
							class="flex-1 tc g3 f28"
							v-if="
								(activeTasks.length > 0 ||
									auditTasks.length > 0) &&
								recallRoot.length === 1
							"
						>
							<image
								style="width: 48rpx; height: 48rpx"
								src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/ytqoccoaza00pi2t8vjyhavos.png"
							></image>
							<view>退回</view>
						</view>
						<view
							@click="handler('add')"
							class="flex-1 tc g3 f28"
							v-if="
								(activeTasks.length > 0 ||
									auditTasks.length > 0) &&
								recallRoot.length === 1
							"
						>
							<image
								style="width: 48rpx; height: 48rpx"
								:src="countersignStatus.image"
							></image>
							<view
								:class="countersignStatus.status ? 'g3' : 'g9'"
								>加签</view
							>
						</view>
						<view
							@click="handler('transfer')"
							class="flex-1 tc g3 f28"
							v-if="
								(activeTasks.length > 0 ||
									auditTasks.length > 0) &&
								recallRoot.length === 1
							"
						>
							<image
								style="width: 48rpx; height: 48rpx"
								src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/gg6am06tp2mtyc06ucv8s7527.png"
							></image>
							<view>转交</view>
						</view>
						<!-- 更多按钮 -->
						<view>
							<view>
								<uni-popup ref="moreMenu">
									<view class="popup-bdf" v-if="isShowMore">
										<view class="df ac p20">
											<view
												@click="handler('comment')"
												class="flex-1 tc g3 mb10 f28"
											>
												<image
													style="
														width: 48rpx;
														height: 48rpx;
													"
													src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/37v3un3ajbxattokrfcw0nqk5.png"
												></image>
												<view>评论</view>
											</view>
											<view
												@click="handler('cancel')"
												class="flex-1 tc g3 f28 mb10"
												v-if="rootTasks.length > 0"
											>
												<image
													style="
														width: 48rpx;
														height: 48rpx;
													"
													:src="cancelStatus.image"
												></image>
												<view
													:class="
														cancelStatus.status
															? 'g3'
															: 'g9'
													"
													>撤销</view
												>
											</view>
											<view
												@click="submitAgain"
												class="flex-1 tc g3 f28"
												v-if="rootTasks.length > 0"
												:class="
													activeTasks.length > 0
														? 'pr20'
														: ''
												"
											>
												<image
													style="
														width: 48rpx;
														height: 48rpx;
													"
													src="https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/qwrzlynz12ygk34udk10ma8ob.png"
												></image>
												<view>再次提交</view>
											</view>
										</view>
										<view
											@tap="cancelShowMore"
											class="cancel-button"
											>取消</view
										>
									</view>
								</uni-popup>
							</view>
						</view>
						<view
							class="flex-1 tc"
							v-if="
								recallRoot.length > 1 &&
								recallRoot[0].user.id == loginUser
							"
						>
							<button
								style="width: 400rpx"
								class="primary-button"
								@tap="reCommit"
							>
								提交
							</button>
						</view>
						<view
							class="flex-1 tc"
							v-if="
								auditTasks.length > 0 ||
								cancelAuditTasks.length > 0
							"
						>
							<button
								style="width: 180rpx"
								class="primary-button"
								@click="handler('audit')"
							>
								办理
							</button>
						</view>
						<view
							class="flex-1 tc"
							v-if="
								(activeTasks.length > 0 ||
									cancelActiveTasks.length > 0) &&
								cancelAuditTasks.length === 0 &&
								auditTasks.length === 0 &&
								recallRoot.length === 1
							"
						>
							<button
								:class="
									rootTasks.length > 0 ||
									activeTasks.length > 0
										? 'w160'
										: 'w100'
								"
								class="delete-button"
								@click="handler('refuse')"
							>
								拒绝
							</button>
						</view>
						<view
							class="flex-1 tc ml10"
							v-if="
								(activeTasks.length > 0 ||
									cancelActiveTasks.length > 0) &&
								auditTasks.length === 0 &&
								cancelAuditTasks.length === 0 &&
								recallRoot.length === 1
							"
						>
							<button
								:class="
									rootTasks.length > 0 ||
									activeTasks.length > 0
										? 'w160'
										: 'w100'
								"
								class="primary-button"
								@click="WeakVerificationStrategy('agree')"
							>
								同意
							</button>
						</view>
					</view>
				</view>
				<processAction
					:isShow="isShowProcessAction"
					:active-tasks="activeTasks"
					:cancelActiveTasks="cancelActiveTasks"
					:action="actionType"
					:auditTasks="auditTasks"
					:action-desc="actionDesc"
					:form-data="formData"
					:instance="instanceData"
					:isSign="isSign"
					@close="close"
				></processAction>
				<!-- 普通弹窗 -->
				<uni-popup ref="popup" type="bottom" background-color="#fff">
					<view class="popup-content">
						<div class="top">
							<div class="title">人脸识别提示</div>
							<div class="close_btn">
								<uni-icons
									@click="closePop"
									type="closeempty"
									color="#9A9A9A"
									size="24"
								></uni-icons>
							</div>
						</div>
						<div class="content">
							<div class="warn">重要提醒：</div>
							<div>
								首次使用该功能，需上传一张您的照片，请确保上传的照片为您本人，且为正面照，五官无被遮挡，否则后续使用时将无法通过人脸识别验证。上传成功后点击【开始人脸识别】，进行人脸识别验证
							</div>

							<div>
								<diy-upload
									limit="1"
									@emitsUrl="emitsReferenceUrl"
								>
									<div class="upload_style">
										<uni-icons
											type="plusempty"
											color="#898989"
											size="24"
										></uni-icons>
										<span style="color: #616161"
											>上传照片</span
										>
									</div>
								</diy-upload>
							</div>
						</div>
						<div class="valley_bottom">
							<div class="cancel" @click="closePop">取消</div>
							<div class="submit" @click="submit">
								开始人脸识别
							</div>
						</div>
					</view>
				</uni-popup>

				<view
					v-if="showCamera"
					style="
						position: absolute;
						z-index: 99;
						top: 0;
						width: 100vw;
					"
				>
					<camera
						device-position="front"
						@initdone="initdone"
						flash="off"
						@error="error"
						style="width: 100vw; height: 80vh"
					></camera>
					<view v-if="showBtn" class="take_photo">
						<div class="btn" @click="uploadCameraImage"></div>
						<div>点击红色按钮拍照</div>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import processProgress from './components/processProgress'
import formDesign from './components/formDesign'
import processAction from './components/processAction'
import associateForm from './components/associateForm'
import diyUpload from '@/subPackagesIndex/components/diy-upload/diy-upload.vue'
import { getWeakVerificationStrategy, weakVerify } from './apis.js'

export default {
	components: {
		processProgress,
		formDesign,
		processAction,
		diyUpload,
		associateForm,
	},
	data() {
		return {
			instanceId: '',
			nodeId: '',
			formId: '',
			instanceData: {},
			dealtStatus: new Map([
				['COMPLETE', '通过'],
				['RUNNING', '进行中'],
				['refuse-end', '审批驳回'],
				['cancel-end', '已撤销'],
			]),
			loginUser: '',
			isShowProcessAction: false,
			actionType: 'agree',
			isShowMore: false,
			selectedCompany: '',
			processList: [],
			referenceImagePath: '',
			cameraImagePath: '',
			cancelProgressList: [],
			showCamera: false,
			showBtn: false,
			isAssociateForm: false,
			associateFormTitle: '',
			associateFormData: [],
		}
	},
	onLoad(options) {
		if (options.q) {
			//微信扫描扫描二维码进来的
			let url = decodeURIComponent(options.q)
			let obj = this.getUrlParam(url)
			console.log('从微信扫码过来obj')
			this.instanceId = obj.instanceId
			this.nodeId = obj.nodeId
			if (options.result === 'true') {
				this.notifyGetImage(options.bytedToken)
			}
		} else {
			this.instanceId = options.instanceId
			this.nodeId = options.nodeId
			this.formId = options.formId
			if (options.result === 'true') {
				this.notifyGetImage(options.bytedToken)
				if (options.bytedToken) {
					this.actionType = 'agree'
					this.isShowProcessAction = true
				}
			}
		}
		if (!uni.getStorageSync('token')) {
			uni.navigateTo({
				url: '/subPackagesIndex/pages/index/authorization/index',
			})
		}
	},
	onShow() {
		this.loginUser = uni.getStorageSync('userId')
		this.getDetailById()
		this.getReadByUserId()
		this.selectedCompany = uni.getStorageSync('selectedCompany').tenantName
		uni.setStorageSync('instanceId', this.instanceId)
	},
	computed: {
		// 是否是用印审批
		isUseSeal() {
			return (
				this.instanceData &&
				this.instanceData.formItems &&
				this.instanceData.formItems.some(
					(item) => item.name === 'TJGJ_YY2'
				)
			)
		},
		// 撤销按钮状态
		cancelStatus() {
			let allowCancel = false
			if (this.instanceData && this.instanceData.settings) {
				allowCancel = this.instanceData.settings.allowCancel
			}
			const endStatus = this.instanceData.status
			const endResult = this.instanceData.result
			if (
				(endStatus === 'RUNNING' && allowCancel) ||
				(endStatus === 'COMPLETE' &&
					endResult === 'process-end' &&
					this.instanceData.cancelProgress.length === 0 &&
					allowCancel)
			) {
				return {
					status: true,
					image: 'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/bxx8r80p5bazwuki6ms5h1rgl.png',
				}
			} else {
				return {
					status: false,
					image: 'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/k093lga66ef3b0qrkon63mcti.png',
				}
			}
		},
		//加签按钮状态
		countersignStatus() {
			const nextApprovalIndex = this.processList.findIndex(
				(i) => i.approvalMode === 'NEXT'
			)
			if (nextApprovalIndex === -1) {
				return {
					status: true,
					image: 'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/45kb81euoo7a4g7quko296dcd.png',
				}
			} else {
				return {
					status: false,
					image: 'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/9y8d2s1vcjyirx7mdtiqudt4k.png',
				}
			}
		},
		status() {
			let status = {}
			if (this.instanceData.status === 'RUNNING') {
				status.color = '#E99D42'
				status.text = this.nodeNumPeopleText()
				status.img = null
			} else if (this.instanceData.status === 'COMPLETE') {
				if (this.instanceData.result === 'refuse-end') {
					status.color = '#FF1717'
					status.text = '审批拒绝'
					status.img =
						'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/anwox7churgzlw99mvqblo9di.png'
				} else if (this.instanceData.result === 'cancel-end') {
					status.color = '#9A9A9A'
					status.text = '已撤销'
					status.img =
						'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/5g1br78v5voe2jyu5md7qp4o2.png'
				} else if (this.instanceData.result === 'process-end') {
					status.color = '#81B337'
					status.text = '审批通过'
					status.img =
						'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/6tpsdgud0igmt27ep435ukwra.png'
				} else if (this.instanceData.result === 'cancel-refuse-end') {
					status.color = '#81B337'
					status.text = '审批通过（撤销被拒绝）'
					status.img =
						'https://yilife-oss-dev-public.oss-cn-hangzhou.aliyuncs.com/34/130595/ORG/6tpsdgud0igmt27ep435ukwra.png'
				}
			}
			return status
		},
		// 退回到发起人视角
		recallRoot() {
			const rootNode = this.processList.filter(
				(i) => i.nodeId === 'root' && !i.result
			)
			return rootNode
		},
		// 发起人视角
		rootTasks() {
			let tasks = []
			;(this.instanceData.progress || []).forEach((task) => {
				if (task.users) {
					task.users.forEach((tk) => {
						if (
							tk.user.id == this.loginUser &&
							tk.nodeType == 'ROOT'
						) {
							tasks.push(tk)
						}
					})
				} else {
					if (
						task.user.id == this.loginUser &&
						task.nodeType == 'ROOT'
					) {
						tasks.push(task)
					}
				}
			})
			return tasks
		},
		// 撤销人审批视角
		cancelActiveTasks() {
			return this.judgeActiveTask(this.instanceData.cancelProgress)
		},
		// 审批人判断视角
		activeTasks() {
			return this.judgeActiveTask(this.instanceData.progress)
		},
		//办理人审批视角
		auditTasks() {
			return this.judgeAuditTasks(this.instanceData.progress)
		},
		cancelAuditTasks() {
			return this.judgeAuditTasks(this.instanceData.cancelProgress)
		},
		actionDesc() {
			switch (this.actionType) {
				case 'agree':
					return { tip: '审批意见', title: '确认同意' }
				case 'refuse':
					return { tip: '审批意见', title: '确认拒绝' }
				case 'comment':
					return { tip: '评论内容', title: '添加评论' }
				case 'add':
					return { tip: '加签备注', title: '加签' }
				case 'audit':
					return { tip: '办理意见', title: '办理完成' }
				case 'beforeAdd':
					return { tip: '加签意见', title: '后方增加审批人' }
				case 'afterAdd':
					return { tip: '加签意见', title: '前方增加审批人' }
				case 'transfer':
					return { tip: '转交备注', title: '转交' }
				case 'cancel':
					return { tip: '撤销理由', title: '撤销当前流程' }
				case 'recall':
					return { tip: '退回备注', title: '退回' }
			}
			return ''
		},
		formData() {
			//过滤出可编辑的表单字段
			let formFields = []
			let formData = {}
			this.getEnableEditForm(
				this.instanceData.formItems || [],
				formFields
			)
			formFields.forEach((k) => {
				this.$set(formData, k, this.instanceData.formData[k])
			})
			return formData
		},
		isSign() {
			if (!Array.isArray(this.instanceData.progress)) return false
			const approvalList =
				this.instanceData & Array.isArray(this.instanceData.progress) &&
				this.instanceData.progress.filter(
					(i) => i.nodeType === 'APPROVAL'
				)
			const andApproval =
				approvalList &&
				approvalList.length > 0 &&
				approvalList.filter(
					(item) =>
						item.approvalMode == 'AND' ||
						item.approvalMode == 'NEXT' ||
						item.approvalMode == 'OR'
				)
			let isSignature = false
			let arr = []

			if (andApproval && andApproval.length > 0) {
				if (Reflect.has(andApproval[0], 'users')) {
					arr = andApproval[0].users.filter((item) => {
						return (
							item.accessMethod === 'SIGN' &&
							item.result === null &&
							item.user.id ===
								String(uni.getStorageSync('userId'))
						)
					})
					isSignature = arr.length === 1
				} else if (Reflect.has(andApproval[0], 'user')) {
					const target = andApproval[0]
					isSignature =
						target.user.id ===
							String(uni.getStorageSync('userId')) &&
						target.accessMethod === 'SIGN' &&
						target.result === null
				}
			}
			return isSignature
		},
		isSealRead() {
			return (
				this.instanceData.formItems &&
				this.instanceData.formItems.some((i) => i.name == 'TJGJ_YY2')
			)
		},
	},
	methods: {
		getReadByUserId() {
			this.$request
				.request('wflow/wflow/seal/file/read/getByUserId', {
					method: 'post',
					data: {
						instanceId: this.instanceId,
						userId: uni.getStorageSync('userId'),
					},
				})
				.then((res) => {
					if (res.success) {
						const list = res.data
						this.$store.commit('setReadFileList', list)
					}
				})
		},
		initdone() {
			this.showBtn = true
		},
		emitCameraImagePath(arr) {
			if (Array.isArray(arr) && arr.length > 0) {
				this.cameraImagePath = arr[0].url
			}
		},
		emitsReferenceUrl(arr) {
			if (Array.isArray(arr) && arr.length > 0) {
				this.referenceImagePath = arr[0].url
			}
		},
		closePop() {
			this.$refs.popup.close()
		},
		error(e) {
			this.showCamera = false
			this.showBtn = false
			uni.showToast({
				title: e.detail,
				icon: 'error',
			})
		},
		uploadCameraImage() {
			const referenceImagePath = this.referenceImagePath
			uni.showLoading()
			const ctx = uni.createCameraContext()
			ctx.takePhoto({
				quality: 'high',
				success: (res) => {
					this.showBtn = false
					this.showCamera = false
					const tempFilePath = res.tempImagePath
					uni.uploadFile({
						url:
							getApp().globalData.uploadDomain +
							'oss-web/oss/upload/file?asyn=false',
						filePath: tempFilePath,
						name: 'file',
						header: {
							tenantId: uni.getStorageSync('orgId'),
							Authorization: uni.getStorageSync('token'),
							reqChannel: getApp().globalData.reqChannel,
						},
						success: (uploadFileRes) => {
							let res = JSON.parse(uploadFileRes.data)
							if (res.success) {
								let data = res.data
								this.cameraImagePath = data.url
								weakVerify(referenceImagePath, data.url)
									.then((res) => {
										uni.hideLoading()
										if (res.data) {
											this.closePop()
											this.$nextTick(() => {
												setTimeout(() => {
													this.actionType = 'agree'
													this.isShowProcessAction = true
												})
											})
										} else {
											// uni.showToast({
											//    title: '认证失败',
											//    icon: 'error',
											// })
											// return
										}
									})
									.catch((err) => {
										uni.hideLoading()
									})

								// }
							} else {
								uni.showToast({
									title: res.message
										? res.message
										: '上传失败~',
									icon: 'error',
								})
							}
						},
						fail(err) {},
					})
				},
			})
		},
		submit() {
			if (!this.referenceImagePath) {
				uni.showToast({
					title: '请上传照片!',
					icon: 'none',
				})
				return
			}
			this.showCamera = true

			//this.uploadCameraImage(this.referenceImagePath);
			// cameraImagePath
		},
		async WeakVerificationStrategy() {
			const approvalList =
				this.instanceData &&
				Array.isArray(this.instanceData.progress) &&
				this.instanceData.progress.filter(
					(i) => i.nodeType === 'APPROVAL'
				)
			const andApproval = approvalList.filter(
				(item) =>
					item.approvalMode === 'AND' ||
					item.approvalMode === 'NEXT' ||
					item.approvalMode === 'OR'
			)
			let isSimpleFace = false
			let arr = []
			if (andApproval && andApproval.length > 0) {
				if (Reflect.has(andApproval[0], 'users')) {
					arr = andApproval[0].users.filter((item) => {
						return (
							item.accessMethod === 'SIMPLE_FACE' &&
							item.result === null &&
							item.user.id ===
								String(uni.getStorageSync('userId'))
						)
					})
					isSimpleFace = arr.length === 1
				} else if (Reflect.has(andApproval[0], 'user')) {
					const target = andApproval[0]
					isSimpleFace =
						target.user.id ===
							String(uni.getStorageSync('userId')) &&
						target.accessMethod === 'SIMPLE_FACE' &&
						target.result === null
				}
			}
			if (isSimpleFace) {
				const resp = await getWeakVerificationStrategy(
					uni.getStorageSync('userId')
				)
				if (resp) {
					if (resp.data === 0) {
						this.$refs.popup.open()
					} else if (resp.data === 1) {
						this.showCamera = true
						// this.uploadCameraImage()
					}
				}
			} else {
				this.handler('agree')
			}
		},
		//判断审批人视角
		judgeActiveTask(list) {
			let tasks = []
			;(list || []).forEach((task) => {
				if (task.users) {
					task.users.forEach((tk) => {
						if (tk.user.id == this.loginUser && !tk.finishTime) {
							tasks.push(tk)
						}
					})
				} else {
					if (task.user.id == this.loginUser && !task.finishTime) {
						tasks.push(task)
					}
				}
			})
			return tasks
		},
		// 判断办理人视角
		judgeAuditTasks(list) {
			let tasks = []
			;(list || []).forEach((task) => {
				if (task.users) {
					task.users.forEach((tk) => {
						if (
							tk.user.id == this.loginUser &&
							tk.nodeType == 'AUDIT' &&
							!tk.finishTime
						) {
							tasks.push(tk)
						}
					})
				} else {
					if (
						task.user.id == this.loginUser &&
						task.nodeType == 'AUDIT' &&
						!task.finishTime
					) {
						tasks.push(task)
					}
				}
			})
			return tasks
		},
		//判断处理人
		nodeNumPeopleText() {
			const nodeList = this.instanceData.assigneeList
			return `${
				nodeList && nodeList.length === 1
					? nodeList[0].name
					: `${nodeList[0].name}等${nodeList.length}人`
			}处理中`
		},
		//有源图片落库
		notifyGetImage(bytedToken) {
			this.$request.request(
				'learn-platform/userVerification/notifyGetImage',
				{
					method: 'post',
					data: {
						bytedToken,
					},
				}
			)
		},
		getUrlParam(url) {
			let params = url.split('?')[1].split('&')
			let obj = {}
			params.map((v) => (obj[v.split('=')[0]] = v.split('=')[1]))
			return obj
		},
		openMoreBtn() {
			this.isShowMore = true
			this.$refs.moreMenu.open('bottom')
		},
		cancelShowMore() {
			this.isShowMore = false
			this.$refs.moreMenu.close()
		},
		close() {
			this.isShowProcessAction = false
			this.isShowMore = false
		},
		handler(action) {
			console.log(
				this.$store.state.sealFileList,
				'----000this.$store.state.sealFileList'
			)
			console.log(
				this.$store.state.readFileList,
				'----this.$store.state.readFileList'
			)
			const approvalList =
				this.instanceData &&
				this.instanceData.progress.length &&
				this.instanceData.progress.filter(
					(i) => i.nodeType === 'APPROVAL'
				)
			const andApproval = approvalList.filter((item) => item.approvalMode)
			let isFinalUser = false // 是否为人脸
			let arr = []
			if (andApproval && andApproval.length > 0) {
				if (Reflect.has(andApproval[0], 'users')) {
					arr = andApproval[0].users.filter(
						(item) =>
							item.result === null &&
							item.user.id ===
								String(uni.getStorageSync('userId')) &&
							item.accessMethod === 'FACE'
					)
					isFinalUser = arr.length === 1
				} else if (Reflect.has(andApproval[0], 'user')) {
					isFinalUser =
						andApproval[0].user.id ===
							String(uni.getStorageSync('userId')) &&
						andApproval[0].result === null &&
						andApproval[0].accessMethod === 'FACE'
				}
			}
			const isSeal =
				this.instanceData &&
				this.instanceData.formItems.length &&
				this.instanceData.formItems.filter(
					(i) => i.name === 'FileUpload' && i.props.userSeal
				).length === 1
			if (
				andApproval &&
				andApproval.length > 0 &&
				isFinalUser &&
				action === 'agree'
			) {
				uni.navigateTo({
					url: `/subPackagesIndex/pages/index/approval/mainSub/webview?instanceId=${this.instanceId}&nodeId=${this.nodeId}`,
				})
			} else if (
				action === 'agree' &&
				this.isSealRead &&
				this.$store.state.sealFileList.length !==
					this.$store.state.readFileList.length
			) {
				uni.showToast({
					title: '还有未读文件',
					icon: 'none',
				})
				return
			} else if (['cancel', 'add'].includes(action)) {
				if (action === 'cancel' && !this.cancelStatus.status) {
					uni.showToast({
						title: '当前审批状态不可使用撤销功能',
						icon: 'none',
					})
					return
				}
				if (action === 'add' && !this.countersignStatus.status) {
					uni.showToast({
						title: '当前节点为会签-顺序审批，无法加签',
						icon: 'none',
					})
					return
				}
				this.actionType = action
				this.isShowProcessAction = true
			} else {
				this.actionType = action
				this.isShowProcessAction = true
			}
		},
		submitAgain() {
			if (this.isUseSeal) {
				uni.showToast({
					title: '请到PC端重新发起',
					icon: 'none',
				})
				return
			} else {
				uni.navigateTo({
					url: `/subPackagesIndex/pages/index/approval/launch/launchApproval?instanceId=${this.instanceId}&code=${this.formId}`,
				})
			}
		},
		reCommit() {
			if (this.isUseSeal) {
				uni.showToast({
					title: '请到PC端提交',
					icon: 'none',
				})
				return
			} else {
				uni.navigateTo({
					url: `/subPackagesIndex/pages/index/approval/launch/launchApproval?instanceId=${
						this.instanceId
					}&code=${this.formId}&instanceData=${encodeURIComponent(
						JSON.stringify(this.instanceData)
					)}&processList=${encodeURIComponent(
						JSON.stringify(this.processList)
					)}`,
				})
			}
		},
		getEnableEditForm(forms, fields) {
			forms.forEach((f) => {
				if (f.name === 'SpanLayout') {
					this.getEnableEditForm(f.props.items, fields)
				} else if (f.perm === 'E') {
					fields.push(f.id)
				}
			})
		},
		getDetailById() {
			uni.showLoading({
				title: '加载中...',
			})
			let url = `wflow/wflow/process/progress/${this.instanceId}/${this.nodeId}`
			this.$request
				.request(url, {
					data: {},
				})
				.then((res) => {
					uni.hideLoading()
					this.instanceData = res
					this.processList = res.progress
					this.instanceData.progress = this.splitByRecall(
						res.progress
					)
					this.$store.commit(
						'setInstanceProgress',
						this.instanceData.progress
					)
					this.cancelProgressList = res.cancelProgress
					this.instanceData.cancelProgress = this.splitByRecall(
						res.cancelProgress
					)
					const { formItems = [] } = res
					let countAssociateForm = 0
					formItems.forEach((item) => {
						if (item.name === 'AssociateForm') {
							countAssociateForm++
						}
						if (item.name === 'FileUpload') {
							countAssociateForm++
						}
					})
					if (countAssociateForm === 2) {
						// 获取
						this.$request
							.request('wflow/wflow/doc/get-process-info', {
								data: {
									processInstanceId: res.instanceId,
								},
							})
							.then((res2) => {
								const res2Data = res2.data
								const { data = {}, items, name } = res2Data
								this.isAssociateForm = true
								const tempData = Object.keys(data).map(
									(item) => {
										const find = items.find(
											(i) => i.formItemId === item
										)
										return {
											key: find ? find.label : item,
											value: data[item],
											type: find ? find.type : '',
										}
									}
								)
								this.associateFormData = tempData
								this.associateFormTitle = name
							})
					}
				})
		},
		//根据退回进行分段拆解
		splitByRecall(progress) {
			//提取分段时间点
			let points = progress
				.filter((p) => p.result === 'recall')
				.map((p) => new Date(p.startTime.replace(/-/g, '/')).getTime())
			if (points.length > 0) {
				let blocks = [] //分段流程块组
				let pointer = 0 //定点索引
				points.push(new Date().getTime())
				points.forEach((point) => {
					let block = []
					for (let i = pointer; i < progress.length; i++) {
						let startTime = new Date(
							progress[i].startTime.replace(/-/g, '/')
						).getTime()
						if (startTime <= point) {
							block.push(progress[i])
						} else {
							pointer = i
							break
						}
					}
					//存段
					blocks.push(block)
				})
				//按段处理
				let processNodes = []
				blocks.forEach((block) =>
					processNodes.push(...this.mergeTask(block))
				)
				return processNodes
			}
			return this.mergeTask(progress)
		},
		//合并活动节点，此处执行一段合并算法用来处理退回导致节点重合的问题
		mergeTask(progress) {
			let merge = []
			progress.forEach((pg) => {
				let i = merge.findIndex((n) => n.nodeId === pg.nodeId)
				if (i > -1) {
					//存在则合并到对象
					if (merge[i].users) {
						//已经合并过了
						merge[i].finishTime = pg.finishTime
						merge[i].users.push(pg)
						merge[i].result = this.getApprovalResult(
							merge[i],
							pg,
							pg.approvalMode
						)
						merge[i].comment = merge[i].comment.concat(pg.comment)
					} else {
						//没有就合并
						merge[i] = {
							agree: null,
							name: pg.name,
							nodeType: pg.nodeType,
							approvalMode: pg.approvalMode,
							nodeId: pg.nodeId,
							result: this.getApprovalResult(
								merge[i],
								pg,
								pg.approvalMode
							),
							startTime: merge[i].startTime,
							finishTime: pg.finishTime,
							comment: merge[i].comment.concat(pg.comment),
							users: [merge[i], pg],
						}
						// merge[i].comment = merge[i].comment.sort((a, b) => moment(a.createTime) - moment(b.createTime))
					}
				} else {
					merge.push(pg)
				}
			})
			return merge
		},

		getApprovalResult(oldVal, newVal, mode) {
			if (mode === 'OR') {
				return newVal.result ? newVal.result : oldVal.result
			} else if (mode === 'AND') {
				let rs = oldVal.result || newVal.result
				return rs === 'recall' ? 'recall' : rs
			} else {
				return newVal.result
			}
		},
		//评论
		comment() {
			this.actionType = 'comment'
			this.isShowProcessAction = true
		},
	},
}
</script>

<style scoped lang="scss">
@mixin bottom_btn {
	width: 162px;
	padding-bottom: 8px;
	padding-top: 8px;
	border: none;
	border-radius: 20px;
	text-align: center;
}

.box {
	background-color: #f5f6f6;
	padding-bottom: 130rpx;
}
.container {
	padding: 32rpx 10rpx 32rpx 32rpx;
	background-color: #fff;
	font-size: 36rpx;
}
.status-image {
	width: 150rpx;
	height: 150rpx;
	position: absolute;
	right: 10%;
	top: 20%;
}
.refuse-button {
	color: $primary-color;
	height: 80rpx;
	line-height: 80rpx;
	border: 2rpx solid $primary-color;
	font-size: 38rpx;
}
.actions {
	padding: 10rpx 5rpx 30rpx;
	position: fixed;
	width: 100%;
	bottom: 0;
	left: 0;
	z-index: 99;
	background: #fff;
	border-top: 2px solid #dcdfe6;
	background: #efefef;
	box-shadow: 0 0 30rpx 0px #dad8d8;
	font-size: 32rpx;
	color: #333333;
}
.w25 {
	width: 25%;
}
/deep/ .uni-forms-item {
	margin-bottom: 0rpx !important;
}
/deep/ .uni-forms-item__label {
	padding-bottom: 0rpx !important;
	color: #9a9a9a !important;
	font-size: 28rpx !important;
}
/deep/ .uni-forms-item__content {
	font-size: 30rpx !important;
	color: #333333 !important;
}
.instance-name {
	color: #9a9a9a;
	margin: 8rpx 0;
	font-size: 28rpx;
}
.popup-content {
	display: flex;
	flex-direction: column;
	padding: 0px;
	.top {
		display: flex;
		position: relative;
		align-items: center;
		box-sizing: border-box;
		padding-right: 19px;
		height: 55px;
		background: linear-gradient(
			90deg,
			rgba(227, 237, 255, 1) -0.1%,
			rgba(223, 234, 255, 0) 100.6%
		);
		.title {
			flex-grow: 1;
			text-align: center;
		}
		.close_btn {
			position: absolute;
			right: 19px;
		}
	}
	.valley_bottom {
		display: flex;
		justify-content: space-around;
		margin-bottom: 10px;
		.cancel {
			@include bottom_btn;
			background: #efefef;
		}
		.submit {
			@include bottom_btn;
			color: #fff;
			background: linear-gradient(90deg, #2d94ff, #b7daff);
		}
	}
	.content {
		padding: 20px;
		flex-grow: 1;
		.warn {
			font-size: 14px;
			color: #bd3124;
		}
		div:nth-child(2) {
			font-size: 14px;
			color: #4c4c4c;
			margin-top: 5px;
			margin-bottom: 10px;
		}
		.upload_style {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 20px;
			.upload {
				width: 100px;
				height: 100px;
				border: 1px dashed #979797;
				border-radius: 5px;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;
				.iconfont {
					font-size: 30px;
					color: #979797;
				}
				.text {
					font-size: 12px;
					color: #979797;
				}
			}
			.img {
				width: 100px;
				height: 100px;
				border-radius: 5px;
				margin-left: 20px;
			}
		}
	}
}
.w160 {
	width: 160rpx;
}
.popup-bdf {
	background: #f2f2f2;
	border-radius: 20rpx 20rpx 0 0;
	padding-top: 30rpx;
}
.cancel-button {
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
	padding: 20rpx;
}

.take_photo {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: fixed;
	width: 100vw;
	height: 20vh;
	z-index: 100;
	bottom: 0;
	background: #fff;
	.btn {
		width: 10vh;
		height: 10vh;
		border-radius: 50%;
		background: red;
		margin-top: 10px;
		margin-bottom: 10px;
	}
}
</style>
